/**
 * @file 操作日志
 * @date 2025/11/18 09:27:14
 * @author lyqjob@yeah.net
 */

import {  useState ,useEffect } from 'react';
import { Table, Space, Modal, Descriptions } from 'antd';
import AuthButton from '@/components/AuthButton';

import { adminApi } from "@/services/admin";
import dayjs from '@/utils/dayjs.js';



const Operlog = () => {
    const [data,setData] = useState([]);
    const [loading,setLoading] =useState(true)
    const [open, setOpen] = useState(false);
    const [loginfo,setLoginfo] = useState({});
    const [pageSize,setPageSize] = useState(10)
    const [current,setCurrent] = useState(1)
    const [total,setTotal] = useState(0)

    const operationTypeMap = {
        create:'创建',
        update:'更新',
        delete:'删除',
        view:'查询',
        export:'导出',
        import:'导入',
        login:'登录',
        logout:'登出',
        other:'其他'
    }



    const columns = [
        { 
            title: '序号', 
            dataIndex: 'operation', 
            key: '' ,
            width:100,
            fixed: 'left',
            render:(text,record,index) => (
                `${index+1}`
            )
        },
        { 
            title: '操作类型', 
            dataIndex: 'action_type', 
            key: '' ,
            ellipsis:true,
            width:150,
            render:(text) => operationTypeMap[text] || '未知'
        },
        { 
            title: '操作模块', 
            dataIndex: 'module_name', 
            key: '' ,
            ellipsis:true,
            width:150,
            render:(text,record) => {
                if(record.business_type === 'login'){
                    return '登录'
                }
                if(record.business_type === 'logout'){
                    return '登出'
                }
                return text
            }
        },
        { title: '操作API', dataIndex: 'url', key: '' ,ellipsis:true,width:200},
        { title: '操作人员', dataIndex: 'opername', key: '' ,width:150},
        { title: '操作IP', dataIndex: 'client_ip', key: '' ,width:150},
        { title: '操作地点', dataIndex: 'location', key: '' ,width:150},
        { 
            title: '操作时间', dataIndex: 'operation_time', key: '' , width:200,
            render:(text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        },
        {
            title:'操作',
            width:150,
            fixed: 'right',
            render:(text,record) => (
                <Space size="small">
                    <AuthButton permission={['operlog:view']}>
                        <a onClick={()=>{viewDetail(record.id)}}>查看详细</a>
                    </AuthButton>
                </Space>
            )
        }
        
    ];



    useEffect(()=>{
        getList(current,pageSize)
    },[])


    // 获取操作日志列表
    const getList = async (page,limit)=>{
        
        const [err,res] = await adminApi.getOperlogs({page,limit});
        if(err){
            setLoading(false)
            // message.warning('获取日志列表失败')
            return
        }
        if(res?.code === 200 && res?.data?.data){
            setLoading(false)
            setData(res.data.data)
            setTotal(res.data.pagination.total)
            window.process.done();
        }

    }


    const handleOk = () => {
        setOpen(false);
    };


    // 查看详细
    const viewDetail = async (id) => {
        const [err,res] = await adminApi.getOperlogById(id);
        if(err){
            // message.warning('获取日志详情失败')
            return
        }
        if(res?.code === 200 && res?.data){
            setLoginfo(res.data)
            setOpen(true)
        }
    }
    
    return (
        <div className="container">
            <Space>
               
            </Space>
            <Table
                loading={loading}
                rowKey={'id'}
                columns={columns}
                rowSelection={false}
                dataSource={data}
                scroll={{
                    x: 1000,
                    y: 450
                }}
                pagination={{
                    pageSize,
                    current,
                    showPage:true,
                    total:total,
                    showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
                    onChange:(page,pageSize)=>{
                        setPageSize(pageSize)
                        setCurrent(page)
                        getList(page,pageSize)
                    }    
                }}
            />

             <Modal
                open={open}
                title="日志详情"
                okText="确定"
                cancelText="取消"
                width={1000}
                okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
                onCancel={() => setOpen(false)}
                destroyOnHidden
                height={600}
                onOk={handleOk}
            >
                <div style={{height:'400px',overflowY:'auto'}}>
                    <Descriptions size="small" title="操作信息" bordered column={3} style={{marginBottom:10}}>
                        <Descriptions.Item label="操作类型">{operationTypeMap[loginfo.action_type] || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="操作模块">{loginfo.module_name || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="操作时间">{dayjs(loginfo.operation_time).format('YYYY-MM-DD HH:mm:ss') || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="操作人员">{loginfo.opername || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="操作IP">{loginfo.client_ip || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="操作地点">{loginfo.location || '未知'}</Descriptions.Item>
                        
                        <Descriptions.Item label="操作API">{loginfo.url || '未知'}</Descriptions.Item>
                    </Descriptions>
                    <Descriptions size="small" title="环境和上下文信息" bordered column={3} style={{marginBottom:10}}>
                        <Descriptions.Item label="操作系统">{loginfo.operating_system || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="浏览器">{loginfo.browser || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="设备类型">{loginfo.device_type || '未知'}</Descriptions.Item>
                        <Descriptions.Item label="Referer">{loginfo.referer || '未知'}</Descriptions.Item>
                    </Descriptions>
                    <Descriptions title="数据变更信息" bordered column={3}>
                        <Descriptions.Item label="操作前数据" span={3}>
                            {loginfo.before_data ? (
                                <pre style={{ 
                                    background: '#f5f5f5', 
                                    padding: '10px', 
                                    borderRadius: '4px',
                                    maxHeight: '200px',
                                    overflow: 'auto',
                                    fontSize: '12px',
                                    margin: 0
                                }}>
                                    {typeof loginfo.before_data === 'string' 
                                        ? loginfo.before_data 
                                        : JSON.stringify(loginfo.before_data, null, 2)}
                                </pre>
                            ) : '无'}
                        </Descriptions.Item>
                        <Descriptions.Item label="操作后数据" span={3}>
                            {loginfo.after_data ? (
                                <pre style={{ 
                                    background: '#f5f5f5', 
                                    padding: '10px', 
                                    borderRadius: '4px',
                                    maxHeight: '200px',
                                    overflow: 'auto',
                                    fontSize: '12px',
                                    margin: 0
                                }}>
                                    {typeof loginfo.after_data === 'string' 
                                        ? loginfo.after_data 
                                        : JSON.stringify(loginfo.after_data, null, 2)}
                                </pre>
                            ) : '无'}
                        </Descriptions.Item>
                    </Descriptions>
                </div>
            </Modal>
        </div>
    )
}


export default Operlog;
